package deepFirstSearch;

import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class P2 {
    List<List<Integer>> ans = new ArrayList<List<Integer>>();
    List<Integer> sequence = new ArrayList<Integer>();

    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        dfs(candidates, target, 0);
        return ans;
    }

    private void dfs(int[] candidates, int target, int start) {
        if (target == 0) {
            ans.add(new ArrayList<>(sequence));
            return;
        }

        for (int i = start; i < candidates.length; i++) {
            if (candidates[i] > target) {
                break;
            }
            if (i > start && candidates[i] == candidates[i - 1]) {
                continue;
            }
            sequence.add(candidates[i]);
            dfs(candidates, target - candidates[i], i + 1);
            sequence.remove(sequence.size() - 1);
        }
    }

    @Test
    public void test01() {
//        int[] candidates = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40};
        int[] candidates = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        int target = 13;
        List<List<Integer>> res = combinationSum2(candidates, target);
        for (List<Integer> re : res) {
            for (Integer ele : re) {
                System.out.print(ele + ", ");
            }
            System.out.println();
        }
    }
}
